var ws;
var connected = false;
var tryonce = false;
var server_addr = "ws://127.0.0.1:18888";//连接本机的端口号
var file = new FileReader();
var msg_handler = {};

// 使用JSON
const CLT_MSG = {   //向后台发送的命令
    //打印文件
    PRINT_IMAGE:27,
    //读卡
    READ_IDCARD : 51,
    //开始循环读卡
    BEGIN_READ_IDCARD : 52,
    //停止循环读卡
    STOP_READ_IDCARD :53,
    //水平
    HCOPY_IDCARD :54,
    //垂直
    VCOPY_IDCARD :55,
    //正面
    PCOPY_IDCARD :56,
    //反面
    NCOPY_IDCARD :57,
};

function onLoadCard(){  //页面load消息 开启并连接后台服务
    if(ws){
        return;
    }

    //output("正在连接：" + server_addr);
    ws = new WebSocket(server_addr);
    ws.onopen = function(evt)
    {
        if(connected)		{ return;}

        connected = true;
        output("已经连接到服务器");
    };

    ws.onclose = function(evt)
    {
        if(!connected)
        {
            if(!tryonce)
            {
                window.location.href = "FLShell://"
                setTimeout("onLoad()", 1000); //修改此处
                tryonce = true;
            }
            else
            {
                setTimeout("onLoad()", 1000);
            }
        }
        else
        {
            output("已断开服务器连接");
            connected = false;
        }

        ws = null;
    }

    ws.onmessage = function(evt)
    {
        if(evt.data.length === 0 ){
            return;
        }

        if(typeof evt.data === 'string'){
            var msg = JSON.parse(evt.data);
            if(msg.err && msg.err !== 0){
                output("错误 - " + msg.err + ", " + msg.msg);
            }
            else if(msg.msg){
                output(msg.msg);
            }

            if(msg.user_data){
                callback[msg.user_data](msg);
                if(typeof msg.user_data === 'number'){
                    callback[msg.user_data] = undefined;
                }
            }
        }
        else{
            var file = new FileReader();
            file.onload = function(evt) {
                if(evt.target.readyState == FileReader.DONE){
                    var data = new Uint8Array(evt.target.result);
                    if(data[0] == SVR_BIN_MSG.CAP_FRAME){
                        return drawImage(data);
                    }
                }
            };

            file.readAsArrayBuffer(evt.data);
        }
    }
}

var context = 1;
var callback = {}

function sendMsg(proto, msg, cb){  //向后台发送的消息处理格式
    if(!ws){
        return;
    }

    if(typeof msg !== 'object'){
        if(typeof msg === 'function')
        {
            cb = msg;
            msg = {};
        }
        else{
            msg = {}
        }
    }

    msg.proto = proto;
    if(typeof cb === 'function'){
        callback[++context] = cb;
        msg.user_data = context;
    }

    ws.send(JSON.stringify(msg));
}

function output(content)
{
    if(content.length ==0){	return;}

    var console = document.getElementById("Console");
    console.value += content;
    console.value += '\r';
    console.scrollTop = console.scrollHeight;
}

function setText(msg) {//显示读到的身份证信息
    document.getElementById("Name").value = msg.strName;
    document.getElementById("Sex").value = msg.strSex;
    document.getElementById("Nation").value = msg.strNation;
    document.getElementById("Born").value = msg.strBirth;
    document.getElementById("Address").value = msg.strAddress;
    document.getElementById("CardNo").value = msg.strID;
    document.getElementById("Police").value = msg.strOrg;
    document.getElementById("ActivityLFrom").value = msg.strVaildityfrom;
    document.getElementById("ActivityLTo").value = msg.strVaildityto;
    document.getElementById("DeviceNo").value = msg.strName;
    document.getElementById("PhotoBuffer").value = msg.base64BMP;
    document.getElementById("PhotoDisplay").src = "data:image/jpg;base64," + msg.base64BMP;
}

function ReadIDCard() //读身份证
{
    return sendMsg(CLT_MSG.READ_IDCARD, function(msg){
        if(msg.err !== 0){ return;}
        setText(msg);
        output("单读卡");
    });

}

callback["idcard"] = function(msg){ //开始读身份证的回调函数，需单独处理，节省内存开销
    if(msg.err !== 0){
        if(msg.err == 150) output("一个正在读卡进程正在读卡，需要先结束读卡");
        return;}
    setText(msg);
    output("读取身份证");
}

function Begin(){ //开始读身份证
    sendMsg(CLT_MSG.BEGIN_READ_IDCARD, {user_data:"idcard"});
    output("开始读卡");
}

function Stop(){ //停止读身份证
    sendMsg(CLT_MSG.STOP_READ_IDCARD, function(msg){
        if(msg.err !== 0){return;}
        output("停止读卡");
    });
}

function HCopy(){ //横向复印
    sendMsg(CLT_MSG.HCOPY_IDCARD, {copy_path:"D:\\"},function(msg){
        if(msg.err !== 0){return;}
        document.getElementById("IDCardDisplay").src = "data:image/jpg;base64," + msg.hcopy;

        sendMsg(CLT_MSG.PRINT_IMAGE,{file:msg.filename},function(msg2){
            if(msg2.err !== 0){ return;}
            output("打印作业号: " + msg2.print_no);
        });
        output("横向复印" + msg.filename);
    });
}

function VCopy(){ //竖向复印
    sendMsg(CLT_MSG.VCOPY_IDCARD, {copy_path:"D:\\"},function(msg){
        if(msg.err !== 0){return;}
        document.getElementById("IDCardDisplay").src = "data:image/jpg;base64," + msg.vcopy;
        sendMsg(CLT_MSG.PRINT_IMAGE,{file:msg.filename},function(msg2){
            if(msg2.err !== 0){ return;}
            output("打印作业号: " + msg2.print_no);
        });
        output("竖向复印" + msg.filename);
    });
}

function PCopy(){ //正面复印
    sendMsg(CLT_MSG.PCOPY_IDCARD, {copy_path:"D:\\"},function(msg){
        if(msg.err !== 0){return;}
        document.getElementById("IDCardDisplay").src = "data:image/jpg;base64," + msg.pcopy;
        sendMsg(CLT_MSG.PRINT_IMAGE,{file:msg.filename},function(msg2){
            if(msg2.err !== 0){ return;}
            output("打印作业号: " + msg2.print_no);
        });
        output("正面复印" + msg.filename);
    });
}

function NCopy(){ //反面复印
    sendMsg(CLT_MSG.NCOPY_IDCARD, {copy_path:"D:\\"},function(msg){
        if(msg.err !== 0){return;}
        document.getElementById("IDCardDisplay").src = "data:image/jpg;base64," + msg.ncopy;
        sendMsg(CLT_MSG.PRINT_IMAGE,{file:msg.filename},function(msg2){
            if(msg2.err !== 0){ return;}
            output("打印作业号: " + msg2.print_no);
        });
        output("反面复印" + msg.filename);
    });
}